import { createRouter, createWebHistory } from "vue-router";

import MovieList from "@/views/MovieList.vue";
import CinemaDetail from "@/views/CinemaDetail.vue";
import Payment from "@/views/Payment.vue";
import SeatSelection from "@/views/SeatSelection.vue";

import CinemaList from "@/views/CinemaList.vue";
import Register from "@/views/Register.vue";
import Myorder from "@/views/Myorder.vue";
import CouponList from "@/views/CouponList.vue";
import MycouponList from "@/views/MycouponList.vue";
import Menber from "@/views/Menber.vue";
import Reying from "@/views/Reying.vue";
import Login from "@/views/Login.vue";
import OrderDetail from "@/views/OrderDetail.vue";
import Refund from "@/views/Refund.vue";
import PaymentFlow from "@/views/PaymentFlow.vue";
import MovieDetail from "@/views/MovieDetail.vue";
import Mycomment from "@/views/Mycomment.vue";

const routes = [
  // 默认路由：打开页面时自动跳转到订单页

  { path: "/", redirect: "/login" },
  { path: "/reying", component: Reying },
  { path: "/login", component: Login },
  { path: "/register", component: Register },
  { path: "/movieList", component: MovieList },

  { path: "/cinemaList", component: CinemaList },
  { path: "/cinemaDetail/:cinemaId", component: CinemaDetail },
  { path: "/seatSelection", component: SeatSelection },
  { path: "/mycomment", component: Mycomment },
  { path: "/myorder", component: Myorder },
  { path: "/couponList", component: CouponList },
  { path: "/mycouponList", component: MycouponList },
  { path: "/member", component: Menber },
  { path: "/payment", component: Payment },
  { path: "/order-detail", component: OrderDetail },
  { path: "/refund", component: Refund },
  { path: "/PaymentFlow/:id?", component: PaymentFlow },
  { path: "/movieDetail", component: MovieDetail },
];

const router = createRouter({
  history: createWebHistory(),
  routes,
});
router.beforeEach((to, from, next) => {
  console.log("路由守卫：", {
    from: from.path,
    to: to.path,
    token: localStorage.getItem("token"),
    userId: localStorage.getItem("userId"),
  });

  // 需要登录的页面
  const requireAuth = [
    "/myorder",
    "/profile",
    "/member",
    "/mycouponList",
    "/payment",
    "/order-detail",
  ];

  const isLoggedIn = !!localStorage.getItem("token");
  const hasUserId = !!localStorage.getItem("userId");

  console.log("登录状态：", { isLoggedIn, hasUserId });

  // 如果目标页面是登录页，直接放行
  if (to.path === "/reying") {
    console.log("目标为登录页，直接放行");
    next();
    return;
  }

  // 检查是否需要登录
  if (requireAuth.includes(to.path)) {
    if (!isLoggedIn || !hasUserId) {
      console.log("需要登录但未登录，跳转到登录页");
      // 保存当前页面信息，登录后跳转回来
      localStorage.setItem("redirectPath", to.path);
      localStorage.setItem("redirectQuery", JSON.stringify(to.query));

      alert("请先登录后再进行操作");
      next("/login");
    } else {
      console.log("已登录，允许访问");
      next();
    }
  } else {
    console.log("不需要登录的页面，直接放行");
    next();
  }
});
export default router;
